/*
 * Kerja Praktek Ebdesk
 */

package com.ebdesk.model.masterdata.database;

import com.ebdesk.model.masterdata.Setting;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 *
 * @author Zulfikar <zulfikarfull@gmail.com>
 */
public class DatabaseData {
    /**
     * ini adalah connection string, tidak null atau kosong, akan di set dalam
     * constructor kemudian immutable.
    */
    private final String connectionString;
    /**
     * ini adalah Nama user database, tidak null atau kosong, akan di set dalam
     * constructor kemudian immutable.
    */
    private final String userName;
    /**
     * ini adalah password user database, tidak null atau kosong, akan di set dalam
     * constructor kemudian immutable.
    */
    private final String password;

    private String driver;
    /**
     * Coonection yang digunakan untuk nyambung database.
     */
    private Connection connection;
    /**
     * Constructor menerima konfigurasi properties file
     *
     * @param properties: properties konfigurasi
    */
    public DatabaseData() throws ClassNotFoundException, IOException, SQLException, NullPointerException {
        Setting setting = new Setting();
        
        
        connectionString = setting.getConnectionstring();
        userName = setting.getUsername();
        password = setting.getPassword();
        // load driver
        driver = setting.getDriver();
        Class.forName(driver);

        // get connection
        connection = getConnection();
    }

    /**
     * Untuk mengambil data di database tergantu sql query masukan.
     *
     * @param sql: query sql.
     *
    */
    public ResultSet queryData(String sql) throws SQLException {
        // execute sql
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();

        return rs;
    }

    public int updateData(String sql) throws SQLException {
        // execute sql
        PreparedStatement ps = connection.prepareStatement(sql);
       
        return ps.executeUpdate();
    }

    public int updateData(PreparedStatement ps) throws SQLException {
        return ps.executeUpdate();
    }

    public PreparedStatement getPreparedStatement(String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }


    private Connection getConnection() throws SQLException {
        return DriverManager.getConnection(connectionString, userName, password);
    }
}
